package com.zsc.wxm.ysh.anjo.house.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.wxm.ysh.anjo.house.cache.AdvertiseCacheService;
import com.zsc.wxm.ysh.anjo.house.feign.OssService;
import com.zsc.wxm.ysh.anjo.house.mapper.AdvertiseMapper;
import com.zsc.wxm.ysh.anjo.house.model.Advertise;
import com.zsc.wxm.ysh.anjo.house.service.AdvertiseService;
import com.zsc.wxm.ysh.anjo.result.PageResult;
import com.zsc.wxm.ysh.anjo.result.Result;
import com.zsc.wxm.ysh.anjo.service.base.enums.resources.AdvertiseStatus;
import com.zsc.wxm.ysh.anjo.service.base.model.resources.dto.AdvertiseDTO;
import com.zsc.wxm.ysh.anjo.service.base.model.resources.qo.AdvertiseQuery;
import com.zsc.wxm.ysh.anjo.service.base.model.resources.vo.AdvertiseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author playmaker
 * @since 2021/3/13 1:05
 */
@Slf4j
@Service
public class AdvertiseServiceImpl extends ServiceImpl<AdvertiseMapper, Advertise> implements AdvertiseService {

    @Resource
    private OssService ossService;

    @Resource
    private AdvertiseCacheService advertiseCacheService;

    @Override
    public void add(AdvertiseDTO param) {
        Advertise item = new Advertise();
        BeanUtils.copyProperties(param, item);
        item.setStatus(AdvertiseStatus.VALID.getValue());
        if (param.getImage() != null) {
            //调用OSS
            Result result = ossService.upload(param.getImage());
            String url = JSON.parseObject(JSON.toJSONString(result.getData().get("url")), String.class);
            item.setImage(url);
        }
        this.save(item);
        //删除缓存
        advertiseCacheService.removeByCache();
    }

    @Override
    public PageResult listPage(AdvertiseQuery query) {
        Page<Advertise> page = new Page<>(query.getCurrPage(), query.getPageSize());
        LambdaQueryWrapper<Advertise> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.orderByDesc(Advertise::getSort);
        if (StringUtils.isNotBlank(query.getTitle())) {
            queryWrapper.like(Advertise::getTitle, query.getTitle());
        }
        if (query.getStatus() != null) {
            queryWrapper.eq(Advertise::getStatus, query.getStatus());
        }
        page = this.baseMapper.selectPage(page, queryWrapper);
        List<Advertise> list = page.getRecords();
        if (CollUtil.isEmpty(list)) {
            return PageResult.ok(Collections.emptyList(), 0);
        }
        List<AdvertiseVO> vos = getAdvertiseVos(list);
        return PageResult.ok(vos, (int) page.getTotal());
    }

    @Override
    public void deleteAdvertise(Long id) {
        this.removeById(id);
        advertiseCacheService.removeByCache();
    }

    @Override
    public AdvertiseVO infoById(Long id) {
        Advertise advertise = this.getById(id);
        AdvertiseVO vo = new AdvertiseVO();
        BeanUtils.copyProperties(advertise, vo);
        vo.setStatus(AdvertiseStatus.getEnumDesc(advertise.getStatus()));
        return vo;
    }

    @Override
    public void updateItem(AdvertiseDTO param) {
        Advertise advertise = this.getById(param.getId());
        BeanUtils.copyProperties(param, advertise);
        this.updateById(advertise);
        advertiseCacheService.removeByCache();
    }

    @Override
    public List<AdvertiseVO> getTopList() {
        List<Advertise> list = advertiseCacheService.listByCache()
                .stream()
                .filter(x -> x.getStatus().equals(AdvertiseStatus.VALID.getValue()))
                .filter(x -> x.getEndTime().toEpochSecond(ZoneOffset.of("+8"))
                        > LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")))
                .sorted(Comparator.comparing(Advertise::getSort))
                .limit(5L)
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        return getAdvertiseVos(list);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        LambdaUpdateWrapper<Advertise> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(Advertise::getStatus, status).eq(Advertise::getId, id);
        this.update(updateWrapper);
        advertiseCacheService.removeByCache();
    }


    private List<AdvertiseVO> getAdvertiseVos(List<Advertise> list) {
        List<AdvertiseVO> vos = new ArrayList<>();
        list.forEach(x -> {
            AdvertiseVO vo = new AdvertiseVO();
            BeanUtils.copyProperties(x, vo);
            vo.setStatus(AdvertiseStatus.getEnumDesc(x.getStatus()));
            vos.add(vo);
        });
        return vos;
    }
}
